{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pull Portfolio Factor Attribution Data with GS Quant\n",
    "\n",
    "First get your portfolio's factor risk report:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from IPython.display import display\n",
    "import warnings\n",
    "from dateutil.relativedelta import relativedelta\n",
    "\n",
    "from gs_quant.markets.portfolio_manager import PortfolioManager\n",
    "from gs_quant.markets.report import FactorRiskViewsMode, FactorRiskTableMode\n",
    "from gs_quant.session import GsSession, Environment\n",
    "\n",
    "GsSession.use(Environment.PROD)\n",
    "warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n",
    "\n",
    "portfolio_id = 'MPWQQ8B05FKPCCH6'\n",
    "risk_model_id = 'BARRA_USFAST'\n",
    "\n",
    "\n",
    "pm = PortfolioManager(portfolio_id)\n",
    "risk_report = pm.get_factor_risk_report(risk_model_id)\n",
    "\n",
    "# Uncomment the two lines below to get active risk data instead\n",
    "#benchmark = SecurityMaster.get_asset(id_value='SPX', id_type=AssetIdentifier.BLOOMBERG_ID)\n",
    "#risk_report = PortfolioManager('ENTER PORTFOLIO ID').get_factor_risk_report(risk_model_id=risk_model_id, benchmark_id=benchmark.get_marquee_id())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then get historical overview of your factor and specific PnL over time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Get Historical PnL and PnL by Type\n",
    "pnl = risk_report.get_factor_pnl(\n",
    "    factor_names=['Factor', 'Specific', 'Total','Market', 'Country', 'Industry', 'Style'],\n",
    "    start_date=risk_report.latest_end_date - relativedelta(years=1),\n",
    "    end_date=risk_report.latest_end_date)\n",
    "\n",
    "pnl_overview = pnl.filter(items=['date', 'Factor', 'Specific', 'Total']).set_index('date')\n",
    "pnl_overview.cumsum().plot(title='PnL Overview')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also break down your factor PnL further by factor category:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "pnl_by_type = pnl.filter(items=['date', 'Market', 'Country', 'Industry', 'Style', 'Specific']).set_index('date')\n",
    "pnl_by_type.cumsum().plot(title='PnL by Factor Category')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is a summary of your most updated factor attribution by factor category:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Get Pnl By Type Table\n",
    "table_data = risk_report.get_view(\n",
    "    mode=FactorRiskViewsMode.Attribution,\n",
    "    start_date=risk_report.latest_end_date - relativedelta(years=1),\n",
    "    end_date=risk_report.latest_end_date).get('factorCategoriesTable')\n",
    "\n",
    "display(pd.DataFrame(table_data).filter(items=['name', 'pnl', 'minExposure', 'maxExposure', 'avgExposure']))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now get a table with your most updated asset PnL by factor:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Get Factor PnL by Asset Table\n",
    "pnl_table = risk_report.get_table(\n",
    "    mode=FactorRiskTableMode.Pnl,\n",
    "    start_date=risk_report.earliest_start_date,\n",
    "    end_date=risk_report.latest_end_date\n",
    ")\n",
    "display(pd.DataFrame(pnl_table))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
